package com.media.selector.media.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.media.selector.MediaSelector
import com.media.selector.R
import com.media.selector.databinding.ItemMediaAlbumBinding
import com.media.selector.media.model.entity.AlbumEntity

/**
 * date        ：2020/4/27
 * author      ：蒙景博
 * description ：
 */
class MediaAlbumAdapter: RecyclerView.Adapter<MediaAlbumAdapter.MediaViewHolder>() {

    private var mSelectionPosition = 0
    private var mOnAlbumItemClickListener: ((position: Int)-> Unit)? = null

    // 异步更新列表
    private val mAsyncListChange by lazy { AsyncListDiffer(this, DiffItemCallback()) }

    init {
        setHasStableIds(true)
    }

    fun notifyAdapterChanged(data: List<AlbumEntity>) {
        mAsyncListChange.submitList(data)
    }

    fun setOnAlbumItemClickListener(listener: (Int)-> Unit) {
        this.mOnAlbumItemClickListener = listener
    }

    fun setSelection(position: Int) {
        this.mSelectionPosition = position
        notifyDataSetChanged()
    }

    override fun getItemId(position: Int) = position.toLong()

    override fun getItemCount(): Int = mAsyncListChange.currentList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
        return MediaViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_media_album, parent, false))
    }

    override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
        val mAlbum = mAsyncListChange.currentList[position]
        holder.binding.mediaAlbumCover.tag = mAlbum
        MediaSelector.with().load(mAlbum.mCoverUri)?.thumbnail(holder.binding.mediaAlbumCover)
        holder.binding.mediaAlbumName.text = mAlbum.getDisplayName(holder.binding.root.context)
        holder.binding.mediaAlbumCount.text = String.format("(%d)", mAlbum.mCount)
        holder.binding.mediaAlbumCheck.visibility = if (mSelectionPosition == position) View.VISIBLE else View.GONE
        holder.binding.root.setOnClickListener { mOnAlbumItemClickListener?.invoke(position) }
    }

    inner class MediaViewHolder constructor(val binding: ItemMediaAlbumBinding): RecyclerView.ViewHolder(binding.root)

    private class DiffItemCallback : DiffUtil.ItemCallback<AlbumEntity>(){
        override fun areItemsTheSame(oldItem: AlbumEntity, newItem: AlbumEntity) = oldItem.hashCode() == newItem.hashCode()
        override fun areContentsTheSame(oldItem: AlbumEntity, newItem: AlbumEntity) = oldItem.mId == newItem.mId && oldItem.mCoverUri == newItem.mCoverUri && oldItem.mCount == newItem.mCount && oldItem.mDisplayName == newItem.mDisplayName
    }
}